package com.byinsight.web.actions.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.byinsight.service.dto.QueryDefinition;
import com.byinsight.web.actions.Constants;
import com.byinsight.web.actions.ErrorCode;

import eg.backend.util.TimeDimension;

public class QueryDefinitionParser extends BaseXMLParser {

	private class QueryDefinitionSAXHandler extends DefaultHandler {
		private StringBuilder text = null;
		
		public void startElement(String namespaceURI, String localName,
				String qName, Attributes atts) throws SAXException {
			if (Constants.QD_ROOT.equalsIgnoreCase(localName)) {
				qd = new QueryDefinition();
			} 
			
//			else if (Constants.QD_TIMEDIM.equalsIgnoreCase(localName)) {
//				String year = atts.getValue(Constants.YEAR);
//				String month = atts.getValue(Constants.MONTH);
//				String week = atts.getValue(Constants.WEEK);
//				TimeDimension td = new TimeDimension();
//				if(month != null)
//					td.setMonth(Integer.parseInt(month));
//				if(year != null)
//					td.setYear(Integer.parseInt(year));
//				if(week != null)
//					td.setWeek(Integer.parseInt(week));
//				qd.setTimeDimension(td);
//			}
			
			text = new StringBuilder();
		}
		
		public void characters(char[] ch, int start, int length) throws SAXException {
			String value = new String(ch, start, length);
			text.append(value);
		}
		
		public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
			if (Constants.QD_START_DATE.equalsIgnoreCase(localName)) {
				Date startDate = DateUtil.StringToDate(text.toString());
				qd.setStartDate(startDate);
			} else if (Constants.QD_END_DATE.equalsIgnoreCase(localName)) {
				Date endDate = DateUtil.StringToDate(text.toString());
				qd.setEndDate(endDate);
			} else if (Constants.QD_TIMEDIM.equalsIgnoreCase(localName)) {
				TimeDimension td = DimensionHelper.toTimeDimension(text.toString());
				qd.setTimeDimension(td);
			} else if (localName.startsWith(Constants.DIM_PREFIX)) {
//				Dimension dim = DimensionHelper.toDimension(localName, text.toString());
				addDimension(qd, text.toString());
			} else if (Constants.QD_VIEWBY.equalsIgnoreCase(localName)) {
				qd.setViewBy(text.toString());
			}
		}
		
		private void addDimension(QueryDefinition qdef, String dimId) {
			if (null == qdef.getDimensions()) {
				List<String> dims = new ArrayList<String>();
				qdef.setDimensions(dims);
			}
			qdef.getDimensions().add(dimId);
		}
	
	}
	
	@Override
	protected DefaultHandler getHandler() {
		return new QueryDefinitionSAXHandler();
	}

	@Override
	protected ErrorCode getParseErrorCode() {
		return ErrorCode.QUERY_DEFINITIN_PARSE_ERROR;
	}

	private QueryDefinition qd;

	public QueryDefinition getQd() {
		return qd;
	}
}
